class Solution
{
public:
    // 通过了，但感觉逻辑还可以优化一下
    long long countSubarrays(vector<int> &nums, int minK, int maxK)
    {
        if (minK > maxK)
        {
            return 0;
        }
        int n = nums.size();
        long long dpLast = 0;
        long long dpCur = 0;
        long long result = 0;
        int lastMin = -1;
        int lastMax = -1;
        int begin = 0;
        for (int i = 0; i < n; ++i)
        {
            if (nums[i] < minK || nums[i] > maxK)
            {
                dpCur = 0;
                lastMin = lastMax = -1;
                begin = i + 1;
            }
            else if (dpLast != 0)
            {
                dpCur = dpLast;
                if (nums[i] == maxK)
                {
                    lastMax = i;
                }
                if (nums[i] == minK)
                {
                    lastMin = i;
                }
                if (nums[i] == minK)
                {
                    dpCur += lastMax - begin;
                    begin = lastMax;
                }
                else if (nums[i] == maxK)
                {
                    dpCur += lastMin - begin;
                    begin = lastMin;
                }
            }
            else
            {
                if (nums[i] == maxK)
                {
                    lastMax = i;
                }
                if (nums[i] == minK)
                {
                    lastMin = i;
                }
                if (lastMax != -1 && lastMin != -1)
                {
                    if (nums[i] == minK)
                    {
                        dpCur = lastMax - begin + 1;
                        begin = lastMax;
                    }
                    else if (nums[i] == maxK)
                    {
                        dpCur = lastMin - begin + 1;
                        begin = lastMin;
                    }
                }
                else
                {
                    dpCur = 0;
                }
            }
            result += dpCur;
            dpLast = dpCur;
        }

        return result;
    }
};
